package com.david.scan

import android.content.Intent
import android.net.Uri
import android.provider.MediaStore
import android.view.View
import android.widget.Toast
import androidx.activity.result.contract.ActivityResultContracts
import com.david.scan.king.BarcodeCameraScanActivity
import com.david.scan.king.DecodeConfig
import com.david.scan.king.analyze.MultiFormatAnalyzer
import com.david.scan.king.util.CodeUtils
import com.google.zxing.Result
import com.king.camera.scan.AnalyzeResult
import com.king.camera.scan.CameraScan
import com.king.camera.scan.analyze.Analyzer
import com.king.camera.scan.util.LogUtils
import com.king.view.viewfinderview.ViewfinderView.ViewfinderStyle


class ScanActivity: BarcodeCameraScanActivity() {
    override fun initCameraScan(cameraScan: CameraScan<Result>) {
        super.initCameraScan(cameraScan)
        // 根据需要设置CameraScan相关配置
        cameraScan.setPlayBeep(true)
    }

    override fun createAnalyzer(): Analyzer<Result> {
        // 初始化解码配置
        val decodeConfig = DecodeConfig().apply {
            // 设置是否支持扫垂直的条码
            isSupportVerticalCode = true
            // 设置是否支持识别反色码，黑白颜色反转
            isSupportLuminanceInvert = true
        }
        // 多格式分析器（支持的条码格式主要包含：一维码和二维码）
        return MultiFormatAnalyzer(decodeConfig)
    }

    /**
     * 布局ID；通过覆写此方法可以自定义布局
     *
     * @return 布局ID
     */
    override fun getLayoutId(): Int {
        return R.layout.activity_scan
    }

    override fun initUI() {
        super.initUI()
        findViewById<View>(R.id.back).setOnClickListener { finish() }
        findViewById<View>(R.id.code_create).setOnClickListener {
            startActivity(Intent(this, CreateQrActivity::class.java))
        }
        findViewById<View>(R.id.img_parse).setOnClickListener {
            startPickPhoto()
        }
    }

    override fun onScanResultCallback(result: AnalyzeResult<Result>) {
        // 停止分析
        //cameraScan.setAnalyzeImage(false)
        // 处理扫码结果相关逻辑（此处弹Toast只是为了演示）
        showResult(result.result.text)
        // 继续分析
        //cameraScan.setAnalyzeImage(true)
    }


    override fun onPause() {
        super.onPause()
        cameraScan.stopCamera()
        cameraScan.setAnalyzeImage(false)

        //viewfinderView.setLaserColor(Color.TRANSPARENT)
    }

    override fun onResume() {
        super.onResume()
        if (resultDialog?.isShowing != true) {
            cameraScan.startCamera()

            cameraScan.setAnalyzeImage(true)
        }
    }







    private val chooseFile = registerForActivityResult(ActivityResultContracts.GetContent()){
        //        FileUtil.getFileRealNameFromUri(this, it)?.let {name ->  Log.e("name", name) }
        //
        //        FileUtil.copyFileToCache(applicationContext, it)

        if (it != null) {
            parsePhoto(it)
        }
    }


    /**
     * 开始选择图片
     */
    private fun startPickPhoto() {
        chooseFile.launch("image/*")


        //val pickIntent = Intent(Intent.ACTION_PICK,
        //    MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        //pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        //startActivityForResult(pickIntent, REQUEST_CODE_PHOTO)
    }

    //override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    //    super.onActivityResult(requestCode, resultCode, data)
    //    if (resultCode == AppCompatActivity.RESULT_OK && data != null) {
    //        if (requestCode == REQUEST_CODE_PHOTO) {
    //            parsePhoto(data)
    //        }
    //    }
    //}

    private fun parsePhoto(uri: Uri) {
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, uri)
            //异步解析
            Thread {
                val result = CodeUtils.parseCode(bitmap)
                runOnUiThread {
                    LogUtils.d("result:$result")
                    showResult(result)
                }
            }.start()
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }


    private var resultDialog: CodeResultDialog? = null
    private fun showResult(text: String?) {
        if (text != null) {
            resultDialog = CodeResultDialog(text, this, R.style.BottomDialogTheme)
            resultDialog?.setOnDismissListener {
                cameraScan.startCamera()
                cameraScan.setAnalyzeImage(true)
                viewfinderView.setViewfinderStyle(ViewfinderStyle.CLASSIC)
                viewfinderView.postInvalidate()
            }
            resultDialog?.show()

            viewfinderView.setViewfinderStyle(-1)
            cameraScan.stopCamera()
            cameraScan.setAnalyzeImage(false)

            viewfinderView.postInvalidate()
        }
        // TODO: 处理结果
        Toast.makeText(this, text, Toast.LENGTH_LONG).show()
    }
}